[Bash] Save part of matching pattern to variable

Posted by Ben on Stack Overflow See other posts from Stack Overflow or by Ben
Published on 2010-04-12T18:15:10Z Indexed on 2010/04/12 21:53 UTC
Read the original article Hit count: 149

Filed under:
|
|
|

I want to extract a substring matching a pattern and save it to a file. An example string:

Apr 12 19:24:17 PC_NMG kernel: sd 11:0:0:0: [sdf] Attached SCSI removable disk

I want to extract the part between the brackets, in this case [].

I tried to do something like grep -e '[$subtext]' to save the text in the brackets to a variable. Of course it doesn't work, but I am looking for a way similar to this. It would be very elegant to include a variable in a regex like this. What can I do best?

Thanks!

© Stack Overflow or respective owner

Related posts about bash

Related posts about regex